package ycl.base.thread;

import lombok.extern.slf4j.Slf4j;
import ycl.common.result.REnum;
import ycl.common.exception.CustomException;

import java.io.*;
import java.nio.file.Files;
import java.util.Objects;

/**
 * 文件复制线程
 *
 * @author ycl
 * @date 2022/6/30 0030 19:10:30
 */
@Slf4j
public class FileCopyThread extends Thread {

	private final String src;//源路径, 带文件名字
	private final String out;//输出路径, 带文件名字

	private final String filename;//文件名

	public FileCopyThread(String src, String out, String filename) {
		this.src = src;
		this.out = out;
		this.filename = filename;
	}

	/**
	 * 1. 源文件位置: /public/{file type}/{filename}
	 * 2. 输出文件位置: {userId}/{file type}/{filename}
	 */
	@Override
	public void run() {
		try {
			File in = new File(src);//源文件
			File dir = new File(out);//目标目录
			dir.mkdirs();//创建目录
			String s1 = out + filename;//上传路径+文件名
			File target = new File(s1);//目标文件
			String suffix = src.substring(src.lastIndexOf(".") + 1);//后缀
			log.info("FileCopyThread --- run --- suffix = {}", suffix);
			if (suffix.equals("txt")) {//文本文件用字符流
				try (Reader r = new FileReader(in);
				     BufferedReader br = new BufferedReader(r);
				     Writer w = new FileWriter(target);
				     BufferedWriter bw = new BufferedWriter(w)
				) {
					String s;
					while (!Objects.equals(s = br.readLine(), ""))
						bw.write(s);
				}
			} else {//其他文件用字节流
				try (InputStream is = Files.newInputStream(in.toPath());
					 BufferedInputStream bis = new BufferedInputStream(is);
					 OutputStream os = Files.newOutputStream(target.toPath());
					 BufferedOutputStream bos = new BufferedOutputStream(os)
				) {
					byte[] b = new byte[8192];
					while (bis.read(b) > 0)
						bos.write(b, 0, b.length);
				}
			}
		} catch (IOException e) {
			log.error("UploadFileUtil ===> uploadFile ===> exception");
			log.error("{}", e.getMessage(), e);
			throw new CustomException(REnum.CUSTOM_FILE_UPLOAD_EXCEPTION);
		}finally {
			Thread.currentThread().interrupt();
		}
	}
}
